<!-- 盘点单-详情 -->
<template>
	<view class="content">
		<!-- 顶部导航栏 -->
		<u-navbar :fixed="false" :title="titleName" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff">
			<view slot="right" @click="openScan">
				<uni-icons v-if="!$utils.isPda()" type="scan" size="24" color="#fff"></uni-icons>
			</view>
		</u-navbar>

		<!-- 表头信息 -->
		<view class="headTabWrap">
			<uni-segmented-control :current="currenTabIndex" :values="items" style-type="text" active-color="#51d0d0"
				@clickItem="onClickItem" />
			<view class="panelBtn" @click="togglePanel()">
				<uni-icons v-if="currenTabIndex==null" type="eye" size="24" color="#51D0D0"></uni-icons>
				<uni-icons v-else type="eye-slash" size="24" color="#8A8A8A"></uni-icons>
			</view>
		</view>

		<view class="headTabContent">
			<view v-show="currenTabIndex === 0">
				<u--form labelPosition="left" :model="formData" labelWidth="80">
					<u-form-item prop="FCode" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform" :size="20"
								color="#808080">{{$utils.toUniCode('&#xed1c;')}}</uni-icons>
							<text class="label-text">单据编号</text>
						</view>
						<u--input :value="formData.FCode" disabled disabledColor="#fff" placeholder="自动生成"
							border="none"></u--input>
					</u-form-item>
					<u-form-item prop="FDate" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform" :size="20"
								color="#808080">{{$utils.toUniCode('&#xe7ac;')}}</uni-icons>
							<text class="label-text">单据日期</text>
						</view>
						<u--input :value="formData.FDate" disabled disabledColor="#fff" border="none"
							placeholder="单据日期"></u--input>
					</u-form-item>
				</u--form>
			</view>
			<view v-show="currenTabIndex === 1">
				<u--form labelPosition="left" :model="formData" labelWidth="80">
					<u-form-item prop="FWarehouseName" borderBottom @click="openBaseScreen('仓库')">
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform" :size="20"
								color="#808080">{{$utils.toUniCode('&#xe689;')}}</uni-icons>
							<text class="label-text">盘点仓库</text>
							<text class="required">*</text>
						</view>
						<u--input :value="formData.FWarehouseName" disabled disabledColor="#fff" placeholder="请选择入库仓库"
							border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item prop="FStorageCode" borderBottom @click="openBaseScreen('库位')">
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform" :size="20"
								color="#808080">{{$utils.toUniCode('&#xeb44;')}}</uni-icons>
							<text class="label-text">盘点库位</text>
							<text class="required">*</text>
						</view>
						<u--input :value="formData.FStorageCode" disabled disabledColor="#fff" placeholder="请选择出库库位"
							border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform" :size="20"
								color="#808080">{{$utils.toUniCode('&#xe713;')}}</uni-icons>
							<text class="label-text">盘点数量</text>
							<text class="required">*</text>
						</view>
						<u--input type="digit" v-model="currentNum" placeholder="请输入盘点数量" clearable
							border="none"></u--input>
					</u-form-item>
				</u--form>
			</view>
		</view>

		<!-- 子表信息 -->
		<view class="detail">
			<!-- 子表页签 -->
			<view class="detail-label">
				<view>盘点明细</view>
			</view>

			<!-- 入库明细 -->
			<view>
				<u-empty v-show="!pagedData.length" icon="/static/image/Img/DataEmpty.png" :style="{height:srvHeight}"
					text="暂无盘点明细"></u-empty>

				<z-paging ref="paging" v-model="pagedData" use-virtual-list auto-show-back-to-top :auto="false"
					:fixed="false" :refresher-enabled="false" :default-page-size="itemsPerPage"
					:paging-style="{'padding':'0px 5px','height':srvHeight}">

					<view class="productRow" v-for="(row,index) in pagedData" :class="scanRow==index ? 'b-p' : 'b-p-t'"
						@click="setScanRow(index)">
						<view class="productRow-title">
							<view style="flex: 1;">【{{index+1}}】{{row.ProductName}}</view>
						</view>
						<view class="productRow-main">
							<view class="total-wrap">
								<text class="total-label">
									帐面数量:
								</text>
								<text class="total-value">
									{{row.zmQty}}
								</text>
							</view>
							<view class="total-wrap">
								<text class="total-label">
									实盘数量:
								</text>
								<text class="total-value">
									{{row.scannedQty}}
								</text>
							</view>
						</view>
						<view class="productRow-main">
							<text class="batch-title">批次</text>
							<text class="pos-title">库位</text>
							<text class="qty-title">帐面数量</text>
							<text class="qty-title">实盘数量</text>
						</view>
						<view class="productRow-sub" v-for="(item,itemIndex) in row.batchCodeArray">
							<view class="batch-content">{{item.batch}}</view>
							<view class="pos-content">
								{{item.posname}}
							</view>
							<view class="qty-content">
								<u--input :value="item.zmqty" disabled disabledColor="#fefefe" fontSize="14px"
									inputAlign="left" color="#666666" border="none"></u--input>
							</view>
							<view class="qty-content" @click.stop="showChange(row,index,item,itemIndex)">
								<text style="color: #666;">{{item.qty}}</text>
							</view>
						</view>
					</view>

				</z-paging>
			</view>

		</view>

		<!-- 子表数值修改弹窗 -->
		<u-modal :show="showChangePanel" :showCancelButton="true" :closeOnClickOverlay="true" confirmColor="#51d0d0"
			:duration="0" title="数量修改" @confirm="confirmChange" @cancel="cancelChange" @close="closeChange">
			<!-- <u--input ref="input" type="digit" v-model="newValue" focus fontSize="20px" color="#666666" border="none"
				clearable placeholder="请输入修改数量"></u--input> -->
			<!-- 适配低性能设备输入框 -->
			<input ref="input" type="digit" v-model="newValue" focus fontSize="20px" color="#666666" border="none"
				clearable placeholder="请输入修改数量"></input>
		</u-modal>

		<!-- PDA扫码 -->
		<m-pda-scancode v-if="$utils.isPda()" listenName="BatchEditScan"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				titleName: '',
				currenTabIndex: 0, // 表头tab当前index
				items: ['基本项', '扫码项'], //	表头tab名称
				scanDisabled: false,
				ifConfirm: false,
				showChangePanel: false,
				currentNum: '', // 本次数量
				scanRow: 0, // 当前扫码行
				headTabWrapHeight: 0, //	表头tab容器高度
				headTabContentHeight: 0, //	表头tab内容高度

				detailLabelHeight: 0, // 切换标签高度
				srvHeight: 'auto', // scrollview高度
				oldValue: '',
				newValue: '',
				posRow: 0,
				posIdx: 0,
				formData: {
					FTakeStockID: 0,
					FCode: '',
					FDate: '',
					FWarehouseID: 0,
					FWarehouseName: '',
					FRKWarehouseID: 0,
					FRKWarehouseName: '',
					FStorageID: 0,
					FStorageCode: '',
					FRKStorageID: 0,
					FRKStorageCode: '',
					Approve: 0
				},
				formDetail: [],
				pagedData: [],
				targetIndexInPage: null, // 目标项在当前分页中的位置
				pageNo: 1, // 起始分页
				itemsPerPage: 30
			}
		},

		created() {

		},

		mounted() {
			let that = this;

			// 监听下拉回调
			uni.$on('BatchEditChoice', function(ret) {
				let selectItem = ret.data;

				if (ret.type == '仓库') {
					if (selectItem.FWarehouseID != that.formData.FWarehouseID) {
						that.formData.FWarehouseID = selectItem.FWarehouseID;
						that.formData.FWarehouseName = selectItem.FWarehouseName;

						that.formData.FStorageID = 0;
						that.formData.FStorageCode = '';
					}
				}

				if (ret.type == '库位') {
					that.formData.FStorageID = selectItem.FStorageID;
					that.formData.FStorageCode = selectItem.FStorageCode;
				}

			})

			// PDA扫码处理
			uni.$on('BatchEditScan', function(content) {
				let scanData = that.$utils.wmsFun.scanTransf(content);
				that.scanHandler(scanData);
			})

			// 动态计算元素高度
			that.getElementHeights();
		},

		methods: {

			// 显示隐藏面板
			togglePanel() {
				if (this.currenTabIndex == null) {
					this.currenTabIndex = 0;
				} else {
					this.currenTabIndex = null;
				}
				this.changeTabContentHeight();
			},

			// 切换表单面板
			onClickItem(e) {
				if (this.currenTabIndex != e.currentIndex) {
					this.currenTabIndex = e.currentIndex;
					this.changeTabContentHeight();
				}
			},

			changeTabContentHeight() {
				const query = uni.createSelectorQuery().in(this);
				this.$nextTick(() => {
					query.select('.headTabContent').boundingClientRect(rect => {
						this.headTabContentHeight = rect.height;
						console.log(this.headTabContentHeight);
						this.calcSrvHeight(this.headTabContentHeight);

					}).exec();
				})
			},

			virtualListChange(vList) {
				console.log(vList);
				// this.pagedData = vList
			},

			// 获取单据详情
			getPageData() {
				let that = this;
				that.$utils.showLoading();
				that.Request.request('batchCode_ckpdDtl', {
						FTakeStockID: that.formData.FTakeStockID
					}, function(res) {
						let data = res.data;

						// 1.初始化表头信息
						that.formData.FDate = data.ds[0].FDate;
						that.formData.FCode = data.ds[0].FCode;
						that.formData.FWarehouseID = data.ds[0].FWarehouseID;
						that.formData.FWarehouseName = data.ds[0].FWarehouseName;
						that.formData.Approve = data.ds[0].Approve;

						// 2.初始化批次码入库明细
						var formDetail = [];
						for (var i in data.ds) {
							var x = 0;
							for (var j in formDetail) {
								if (formDetail[j].ProductCode == data.ds[i].ProductCode) {
									x = 1;
									formDetail[j].batchCodeArray.push({
										FStockDeID: data.ds[i].FStockDeID,
										batch: data.ds[i].FBatchNo,
										zmqty: data.ds[i].ZMQty,
										qty: data.ds[i].FQty,
										posid: data.ds[i].FStorageID,
										posname: data.ds[i].FStorageCode
									})
								}
							}

							if (x == 0) {
								formDetail.push({
									// ProductID: data.ds[i].ProductID,
									ProductCode: data.ds[i].ProductCode,
									ProductName: data.ds[i].ProductCode,
									zmQty: 0,
									scannedQty: 0,
									batchCodeArray: [{
										FStockDeID: data.ds[i].FStockDeID,
										batch: data.ds[i].FBatchNo,
										zmqty: data.ds[i].ZMQty,
										qty: data.ds[i].FQty,
										posid: data.ds[i].FStorageID,
										posname: data.ds[i].FStorageCode
									}]
								})
							}
						}

						formDetail.forEach((row, index) => that.calcRowTotal(row));
						that.formDetail = formDetail;

						that.$refs.paging.setLocalPaging(formDetail);
						that.$utils.hideLoading();
					},
					function(err) {}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 设置扫码物料行
			setScanRow(index) {
				this.scanRow = index;
			},

			showChange(row, index, item, itemIndex) {
				if (!this.formData.Approve) {
					this.showChangePanel = true;
					this.isFocused = true;
					this.oldValue = item.qty;
					this.newValue = item.qty;
					this.posRow = index;
					this.posIdx = itemIndex;
				}
			},

			confirmChange() {
				var value = this.newValue;

				if (!value) {
					this.$utils.msg('数量不能为零或空!');
				} else {
					let row = this.formDetail[this.posRow];
					let item = row.batchCodeArray[this.posIdx];

					if (Number(value) != this.oldValue) {
						this.$utils.msg('数量修改成功!');
						item.qty = Number(value);
						this.calcRowTotal(row);
					}
				}

				this.showChangePanel = false;
				this.isFocused = false;
			},

			cancelChange() {
				this.showChangePanel = false;
				this.isFocused = false;
			},

			closeChange() {
				this.showChangePanel = false;
				this.isFocused = false;
			},


			// 计算合计扫码数量
			calcRowTotal(row) {
				// 物料账面数量合计
				const zmTotal = row.batchCodeArray.reduce((acc, item) => acc + Number(item.zmqty), 0);
				// 物料已盘数量合计
				const spTotal = row.batchCodeArray.reduce((acc, item) => acc + Number(item.qty), 0);
				row.zmQty = zmTotal;
				row.scannedQty = spTotal;
			},

			// 打开摄像头
			openScan() {
				let that = this;
				this.$scanPopup.openScan({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: (res) => {
						let scanData = that.$utils.wmsFun.scanTransf(res.result);
						that.scanHandler(scanData);
					}
				})
				/* uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: function(res) {
						let scanData = that.$utils.wmsFun.scanTransf(res.result);
						that.scanHandler(scanData);
					}
				}) */
			},

			// 扫码处理
			scanHandler(scanData) {
				let that = this;

				if (that.scanDisabled) {
					that.$utils.msg('数据提交中,请稍后再试!');
					return false;
				}
				if (!scanData) {
					that.$utils.msg('请扫描正确的条码!');
					return false;
				}

				if (scanData.type == '产品批次码') {


					if (!that.formData.FStorageCode) {
						that.currenTabIndex = 1;

						that.$utils.msg('请选择盘点库位!')
						return false;
					}

					if (!that.currentNum) {
						that.currenTabIndex = 1;

						that.$utils.msg('请输入盘点数量!')
						return false;
					}

					// 当前盘点信息 物料编码、库位、批次
					let takeStockInfo = {
						ProductCode: scanData.data.code,
						FStorageID: that.formData.FStorageID,
						FStorageCode: that.formData.FStorageCode,
						FBatchNo: scanData.data.batch,
						Qty: that.currentNum
					}
					console.log(that.pagedData);
					let matchProduct = that.formDetail.find(item => item.ProductCode == takeStockInfo.ProductCode);
					if (matchProduct == undefined) {
						that.$utils.msg('盘点物料不存在!');
						return false;
					} else {
						let matchProductIndex = that.formDetail.findIndex(item => item.ProductCode == takeStockInfo
							.ProductCode);
						let matchBatch = matchProduct.batchCodeArray.find(item => item.batch == takeStockInfo
							.FBatchNo &&
							item.posid == takeStockInfo.FStorageID);
						if (matchBatch == undefined) {
							that.$utils.msg('库位批次不存在!');
							return false;
						} else {
							matchBatch.qty = takeStockInfo.Qty;
							// 调用接口直接更新当前库位批次实盘数量
							that.calcRowTotal(matchProduct);
							that.setScanRow(matchProductIndex);
							const targetPage = Math.ceil((matchProductIndex + 1) / that.itemsPerPage); // 目标分页
							// that.$refs.paging.refreshToPage(targetPage);
							// setTimeout(() => {
							// 	that.$refs.paging.scrollIntoViewByIndex(matchProductIndex);
							// }, 2000)
							// const pagingRef = ref()
							// 修改前
							// const jumpTo = async function() {
							const jumpTo = that.$refs.paging.refreshToPage(targetPage);
							jumpTo.then((result) => {
								console.log(result);
								that.$refs.paging.scrollIntoViewByIndex(matchProductIndex);
							})
							// }
							// jumpTo()
							// const refreshPromise = that.$refs.paging.refreshToPage(targetPage);
							// refreshPromise.then(result => {
							// 	that.$refs.paging.reload();
							// 	that.$refs.paging.setLocalPaging(result.totalList);
							// 	that.$refs.paging.scrollIntoViewByIndex(matchProductIndex);
							// 	console.log(result);
							// })
						}
					}

					// let valParams = {
					// 	FWarehouseID: that.formData.FWarehouseID,
					// 	FStorageCode: that.formData.FStorageCode,
					// 	ProductCode: scanData.data.code,
					// 	FBatchNo: scanData.data.batch
					// }

					// that.scanDisabled = true;
					// // 验证批次条码库存信息
					// that.Request.request('batchCode_dbdYz', valParams, function(res) {
					// 		that.scanDisabled = false;

					// 		let data = res.data;
					// 		if (data.ds[0].status == 500) {
					// 			that.$utils.msg(data.ds[0].msg);
					// 		} else {
					// 			// 当前选中物料行
					// 			var matchRow;
					// 			var matchIndex;

					// 			// 批次条码信息
					// 			var batchCode = {
					// 				FStockDeID: 0,
					// 				batch: scanData.data.batch,
					// 				qty: Number(that.currentNum),
					// 				posid: that.formData.FStorageID, // 调出货位
					// 				posname: that.formData.FStorageCode,
					// 				posid2: that.formData.FRKStorageID, // 调入货位
					// 				posname2: that.formData.FRKStorageCode
					// 			}

					// 			let flag = that.formDetail.some(item => item.ProductCode == scanData.data.code);
					// 			// 新增物料扫码行
					// 			if (!flag) {
					// 				that.formDetail.push({
					// 					ProductCode: scanData.data.code,
					// 					ProductName: data.ds[0].ProductName,
					// 					scannedQty: 0,
					// 					batchCodeArray: []
					// 				})
					// 				matchRow = that.formDetail[that.formDetail.length - 1];
					// 				matchIndex = that.formDetail.length - 1;
					// 			} else {
					// 				matchRow = that.formDetail.find(item => item.ProductCode == scanData.data.code);
					// 				matchIndex = that.formDetail.findIndex(item => item.ProductCode == scanData.data
					// 					.code);
					// 			}
					// 			matchRow.batchCodeArray.push(batchCode);
					// 			that.setScanRow(matchIndex);
					// 			that.calcRowTotal(matchRow, matchIndex);
					// 			that.scanDisabled = false;
					// 		}
					// 	}, function(err) {
					// 		that.scanDisabled = false;
					// 	}, that.Request.IPAgreement() + that.Request.serverIP() +
					// 	'/Frame/SqlData', 1)

				} else if (scanData.type == '库位') {

					let obj = {
						QrQZ: scanData.data.tag,
						QrCode: scanData.data.code,
						FWarehouseID: that.formData.FWarehouseID
					}

					that.scanDisabled = true;
					that.Request.request('Get_QrStorage', obj, function(res) {
							that.scanDisabled = false;

							let data = res.data;
							if (data.ds[0].status == 500) {
								that.$utils.msg(data.ds[0].msg)
							} else {
								that.formData.FStorageID = data.ds[0].FStorageID;
								that.formData.FStorageCode = data.ds[0].FStorageCode;
							}
						}, function(err) {
							that.scanDisabled = false;
						}, that.Request.IPAgreement() + that.Request.serverIP() +
						'/Frame/SqlData', 1)

				}
			},

			// 获取相关元素高度
			getElementHeights() {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					const promises = [];
					// 获取每个元素的高度，并返回一个 Promise
					const getHeightPromise = (selector) => {
						return new Promise((resolve) => {
							query.select(selector).boundingClientRect((rect) => {
								resolve(rect.height);
							}).exec();
						});
					};

					promises.push(getHeightPromise('.headTabWrap'));
					promises.push(getHeightPromise('.headTabContent'));
					promises.push(getHeightPromise('.detail-label'));
					promises.push(getHeightPromise('.bottom'));

					// 等待所有 Promise 完成
					Promise.all(promises).then((heights) => {
						console.log(heights);
						this.headTabWrapHeight = heights[0];
						this.headTabContentHeight = heights[1];
						this.detailLabelHeight = heights[2];
						this.bottomHeight = heights[3];

						this.calcSrvHeight(this.headTabContentHeight);
					});
				})
			},

			// 重新计算scrollview高度
			calcSrvHeight(headTabContentHeight) {
				let safeAreaTop = this.$u.sys().statusBarHeight;
				let height =
					`calc(100vh - 44px - ${safeAreaTop}px - ${this.headTabWrapHeight}px - ${headTabContentHeight}px - ${this.detailLabelHeight}px - ${this.bottomHeight}px)`;
				this.srvHeight = height;
				console.log(this.srvHeight);
			},

			// 公共下拉选择
			openBaseScreen(str) {
				let url = '/commonPage/Tool/baseScreen';
				let obj;

				if (str == '仓库') {
					obj = {
						allowClear: false,
						cmd: 'Droplist_Warehouse',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							showText: 'FWarehouseName', //查询结果显示的字段
							ChoiceDataKey: 'FWarehouseID',
							ChoiceDataData: this.formData.FWarehouseID
						},
						param: {

						}
					}
				}

				if (str == '库位') {
					if (!this.formData.FWarehouseID) {
						this.$utils.msg('请先选择盘点仓库!');
						return false;
					}

					obj = {
						allowClear: false,
						cmd: 'Droplist_Storage',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							searchKey: 'FStorageCode',
							showText: 'FStorageCode', //查询结果显示的字段
							ChoiceDataKey: 'FStorageID',
							ChoiceDataData: this.formData.FStorageID
						},
						param: {
							FWarehouseID: this.formData.FWarehouseID
						}
					}
				}

				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'BaseScreenParm',
					data: obj
				})

				uni.navigateTo({
					url: url
				})
			}
		},

		onLoad(option) {
			let menuName = decodeURIComponent(option.menuName);
			this.titleName = menuName + '详情';
			this.formData.FTakeStockID = parseInt(option.FStockID);

			if (this.formData.FTakeStockID != 0) {
				this.getPageData();
			}
		},

		onUnload() {
			uni.$off('BatchEditChoice');
			uni.$off('BatchEditScan');
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/static/assets/scss/wms.scss";

	.batch-title,
	.batch-content {
		width: 40%;
	}

	.qty-title,
	.qty-content {
		width: 20%;
	}

	.pos-title,
	.pos-content {
		width: 20%;
	}
</style>